package sample;/**
 * Created by CXinZhi on 2016/10/25.
 */

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import sample.compare.CompareDirectory;
import sample.compare.CompareExcel;
import sample.compare.CompareFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.*;

public class Compare extends Application {

	public static void main(String[] args) {
		launch(args);
	}

	List<CompareExcel> listCom ;

	@Override
	public void start(Stage primaryStage) throws IOException {
		try {
			Class<?> macFontFinderClass = Class.forName("com.sun.t2k.MacFontFinder");
			Field psNameToPathMap = macFontFinderClass.getDeclaredField("psNameToPathMap");
			psNameToPathMap.setAccessible(true);
			psNameToPathMap.set(null, new HashMap<String, String>());
		} catch (Exception e) {
			// ignore
		}

		Parent root = FXMLLoader.load(getClass().getResource("compare.fxml"));
		primaryStage.setTitle("EC 1.0 for xls");
		primaryStage.setScene(new Scene(root, 1024, 768));

		final Button btnCom = (Button) root.lookup("#btnStartCom");

		final TextField txtDir1 = (TextField) root.lookup("#txtDir1");
		final TextField txtDir2 = (TextField) root.lookup("#txtDir2");

		final Label lblResult = (Label) root.lookup("#lblResult");
		final TextArea txtDetail = (TextArea) root.lookup("#txtDetail");

		btnCom.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {

				listCom = new ArrayList<CompareExcel>();
				StringBuilder megDetail = new StringBuilder();
				lblResult.setText("");
				txtDetail.setText("");

				String path1 = txtDir1.getText();
				String path2 = txtDir2.getText();

				if(!isExistDir(path1))
				{
					txtDetail.setText("                路径1不存在，请重新输入！");
					return;
				}

				if(!isExistDir(path2))
				{
					txtDetail.setText("                路径2不存在，请重新输入！");
					return;

				}


				startCompareByPath(path1, path2);

				Integer intSuccess = 0;
				Integer intError = 0;

				megDetail.append("         本次匹配结束\n\n\n");

				Collections.sort(listCom, new Comparator<CompareExcel>() {
					public int compare(CompareExcel arg0, CompareExcel arg1) {
						return arg0.getMatch().compareTo(arg1.getMatch());
					}
				});

				for (CompareExcel ce : listCom) {
					megDetail.append(ce.getMatchMeg()+"\n");

					if (ce.isMatch())
						intSuccess++;
					else
						intError++;
				}

				lblResult.setText(String.format("本次匹配共 %s 文件，成功匹配  %s 个，失败匹配 %s",(intSuccess+intError),
						intSuccess,intError));

				txtDetail.setText(megDetail.toString());
		}
		});
		primaryStage.show();
	}


	/**
	 * 通过目录进行对比两个目录下的 EXCEL
	 *
	 * @param path1
	 * @param path2
	 */
	public void startCompareByPath(String path1, String path2) {

		int rootLevel = 0;

		CompareDirectory rootDirec1 = new CompareDirectory(rootLevel, "根目录", path1, "");
		CompareDirectory rootDirec2 = new CompareDirectory(rootLevel, "根目录", path2, "");

		// 加载 根目录1 下所有的 excle
		loadFile(rootDirec1, path1);

		// 加载 根目录2 下所有的 excle
		loadFile(rootDirec2, path2);

		// 开始匹配
		startCompare(rootDirec1, rootDirec2);

	}

	/**
	 * 开始进行匹配
	 */
	public void startCompare(CompareDirectory directory1, CompareDirectory directory2) {

		System.out.println(String.format("\n当前路径级别[%s],匹配文件夹路径[%s] ,文件数[%s]", directory1.getLevel(),
				directory1.getDirectoryPath(), directory1.getFileList().size()));

		for (CompareFile file : directory1.getFileList()) {
			CompareFile comFile = findCompareFile(directory1.getLevel(), file.getFielName(), directory1.getRelatPath(),
					directory2);

			if (comFile == null)
				continue;

			compareExcel(file, comFile);
		}

		if (directory1.getChildDirectorys().size() < 0)
			return;

		for (CompareDirectory dir : directory1.getChildDirectorys()) {
			startCompare(dir, directory2);
		}


	}


	/**
	 * fine the file in the 1_0 path
	 *
	 * @param level
	 * @param fileName
	 * @param directory2
	 * @return
	 */
	private CompareFile findCompareFile(Integer level, String fileName, String relatPath,
										CompareDirectory directory2) {

		if (level != directory2.getLevel()) {
			for (CompareDirectory dir : directory2.getChildDirectorys()) {

				CompareFile file = findCompareFile(level, fileName, relatPath, dir);

				if (file != null)
					return file;
			}
		}

		for (CompareFile file : directory2.getFileList()) {
			if (file.getFielName().equals(fileName) && directory2.getRelatPath().equals(relatPath)) {
				return file;
			}
		}

		return null;

	}

	/**
	 * 开始匹配文件内容
	 *
	 * @param compareFile1
	 * @param compareFile2
	 */
	private void compareExcel(CompareFile compareFile1, CompareFile compareFile2) {

		System.out.println(String.format("%s 匹配文件夹路径1:[%s]", "	", compareFile1.getFilePath()));
		System.out.println(String.format("%s 匹配文件夹路径2:[%s]", "	", compareFile2.getFilePath()));

		CompareExcel compareExcel = new CompareExcel();
		compareExcel.getMatchMeg().append(String.format("%s 匹配文件夹路径1:[%s] \n", "	", compareFile1.getFilePath
				()));
		compareExcel.getMatchMeg().append(String.format("%s 匹配文件夹路径2:[%s] \n", "	", compareFile2.getFilePath
				()));
		compareExcel.compareFile(compareFile1.getFilePath(), compareFile2.getFilePath());
		listCom.add(compareExcel);
	}


	/**
	 * 加载目录下所有文件 和 目录信息
	 *
	 * @param compareDirectory
	 */
	public void loadFile(CompareDirectory compareDirectory, String rootPath) {

		try {
			Integer level = compareDirectory.getLevel() + 1;

			File root = new File(compareDirectory.getDirectoryPath());

			File[] list = root.listFiles();

			List<CompareFile> files = new ArrayList<CompareFile>();

			if (list == null) return;

			for (File f : list) {
				if (f.isDirectory()) {

					// 下一级别对比文件夹
					CompareDirectory childDirectory = new CompareDirectory(level, f.getName(),
							f.getAbsolutePath(), getSubPath(rootPath, f.getAbsolutePath()));
					compareDirectory.getChildDirectorys().add(childDirectory);

					//加载 下一级别的文件夹内容
					loadFile(childDirectory, rootPath);

					//	System.out.println("Dir:" + f.getAbsoluteFile());
				} else if (f.isFile() && f.getName().contains("xls")) {

					// 加载对比文件
					CompareFile compareFile = new CompareFile(level, f.getName(), f.getAbsolutePath());
					compareDirectory.getFileList().add(compareFile);
					//	System.out.println("File:" + f.getAbsoluteFile());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String getSubPath(String rootPath, String abPath) {
		return abPath.replace(rootPath, "");
	}

	/**
	 * 获得用户界面输入内容
	 *
	 * @return
	 */
	private String catchInput() throws IOException {

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

		String strIn = bufferedReader.readLine();

		File root = new File(strIn);

		if (root.isDirectory())
			return strIn;
		else {
			System.out.println("该路径不存在，请重新输入！");
			return catchInput();
		}
	}


	private boolean isExistDir(String str)
	{

		File root = new File(str);

		if (root.isDirectory())
			return true;
		else {
			return false;
		}
	}


}
